import os
import threading
from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route('/', methods=['GET'])
def hello():
    return 'hello world!'


@app.route('/spider1688', methods=['POST'])
def spider1688():
    crawl_url = request.json['crawl_url']
    print(crawl_url)
    if crawl_url is not None and len(crawl_url) != 0:
        t = threading.Thread(target=start_crawl, args=(crawl_url,))
        t.setDaemon(True)
        t.start()

    return jsonify({"success": True})


def start_crawl(start_url):
    cmd = 'scrapy crawl spider_1688 -a start_urls=' + start_url + ' --nolog'
    output = os.popen(cmd)
    print(output.read())


if __name__ == '__main__':
    app.run(port=5001, debug=True)
